import pandas as pd
import akshare as ak
from datetime import date, timedelta, datetime
import time
from cachetools import TTLCache
import random

code_cache = TTLCache(maxsize=1000000, ttl=86400)  # 股票代码缓存24小时
hist_cache = TTLCache(maxsize=1000000, ttl=86400)   # 历史数据缓存1小时
#print(ak.stock_info_sz_name_code().head())

def fetch_stock_list_from_sina():
    #from app.controllers.predict_controller import cache
    """使用 AKShare 获取沪深股票列表（替代新浪财经爬虫）"""
    print("fetch")
    try:
        start_date = '2024-10-10'
        yesterday = datetime.now() - timedelta(days=1)
        end_date = f"{yesterday.year}-{yesterday.month}-{yesterday.day}"
        adj = 'hfq'
        period = 'daily'
        #print(end_date)
        all_stocks = []
        code_list1 = []
        #
        cache_key_codes = "stock_codes_sh"
        code_list1 = code_cache.get(cache_key_codes)
        #
        # 获取所有A股实时行情数据
        sh_stocks = ak.stock_info_sh_name_code()
        sz_stocks = ak.stock_info_sz_name_code()
        #print(sh_stocks.head())
        #
        code_list1 = sh_stocks['证券代码'].to_list()
        code_list2 = sz_stocks['A股代码'].to_list()
        code_list1 = code_list2[:100] + code_list1[:100]
        code_cache[cache_key_codes] = code_list1
        #code_list1 = sh_stocks['证券代码'].to_list()
        #
        #print(code_list1)
    except Exception as e:
        print(f"失败: {str(e)}")
    for code in code_list1:  # 测试时先限制10只股票
        time.sleep(0.05)
        try:
            # 获取单只股票历史数据
            #print(code)
            #
            cache_key_hist = f"stock_hist_{code}"
            cached_data = hist_cache.get(cache_key_hist)
            '''
            stock_df = ak.stock_zh_a_hist(
                symbol=code,
                period=period,
                start_date=start_date
                #adjust=adj
            )
            print("日期列数据类型:", stock_df['日期'].dtype)
            print(stock_df)'''
            #
            if cached_data is not None:
                print(f"股票 {code} 数据从缓存读取")
                stock_df = cached_data
            else:
                print(f"从接口获取股票 {code} 历史数据...")
                stock_df = ak.stock_zh_a_hist(
                    symbol=code,
                    period=period,
                    start_date=start_date
                )
                hist_cache[cache_key_hist] = stock_df  # 缓存历史数据
                print(f"股票 {code} 数据已缓存")

            # 数据清洗
            stock_df.rename(
                columns={
                    '日期': '交易日期',
                    '收盘': '收盘价'
                },
                inplace=True
            )

            # 添加股票代码列
            stock_df['股票代码'] = code

            # 选择需要的列
            stock_df = stock_df[['交易日期', '股票代码', '收盘价']]

            all_stocks.append(stock_df.tail(30))
            print(all_stocks)
        except Exception as e:
            print(f"股票 {code} 获取失败: {str(e)}")
            continue

    # 合并所有股票数据
    if all_stocks:
        result = pd.concat(all_stocks, ignore_index=True)
        print(f"最终合并数据，共 {len(result)} 条记录")
        return result
    return pd.DataFrame()

